import React, { useEffect } from 'react';
// @ts-ignore
import * as THREE from 'three';
// @ts-ignore
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const Demo1: React.FC = () => {
  const init = () => {
    const container = document.getElementById('webgl');
    if (container) {
      container.innerHTML = '';
    }
    // 创建3D场景对象Scene
    const scene = new THREE.Scene();
    //创建一个长方体几何对象Geometry
    const geometry = new THREE.BoxGeometry(100, 60, 20);
    //创建一个材质对象Material
    const material = new THREE.MeshBasicMaterial({
      color: 0x0000ff, //设置材质颜色
      transparent: true, //开启透明
      opacity: 0.5, //设置透明度
    });
    // 两个参数分别为几何体geometry、材质material
    const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
    //设置网格模型在三维空间中的位置坐标，默认是坐标原点
    mesh.position.set(0, 0, 0);
    scene.add(mesh);

    // AxesHelper：辅助观察的坐标系
    const axesHelper = new THREE.AxesHelper(150);
    scene.add(axesHelper);

    const width = 800; //宽度
    const height = 500; //高度

    // 实例化一个透视投影相机对象
    const camera = new THREE.PerspectiveCamera(20, width / height, 0.1, 3000);
    camera.position.set(300, 300, 300);
    camera.lookAt(0, 0, 0);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height); //设置three.js渲染区域的尺寸(像素px)
    renderer.setClearColor('#ffffff', 1); //设置背景颜色

    renderer.render(scene, camera); //执行渲染操作
    container?.appendChild(renderer.domElement);
    // 设置相机控件轨道控制器OrbitControls
    const controls = new OrbitControls(camera, renderer.domElement);
    // 如果OrbitControls改变了相机参数，重新调用渲染器渲染三维场景
    controls.addEventListener('change', function () {
      renderer.render(scene, camera); //执行渲染操作
    }); //监听鼠标、键盘事件
  };
  useEffect(() => {
    init();
  }, []);
  return <div id="webgl"></div>;
};

export default Demo1;
